import React from "react";
import { Route, NavLink, Switch, withRouter, Redirect } from "react-router-dom";

import Header from "./components/Header";
import Home from "./pages/Home/index";
import About from "./pages/About";
import Help from "./pages/Help";
import Detail from "./pages/Detail";
import Login from "./pages/Login";

// 写一个组件，名叫 AuthRoute
//  这个组件内 渲染的 是 Route 且做好 登录的校验
//  <AuthRoute path="/about" name="1" component={About} />
//  <AuthRoute path="/help" exact component={Help} />
//  <AuthRoute path="/detail/:id" component={Detail} />

/**
 * // 组件组合
 *    1. component 收到的是一个组件，组件使用时，首字母必须大写
 */
function AuthRoute({ component: Component, ...rest }) {
  // console.log(component) => About
  // console.log(rest)  => { path: '/about' , name: "1" }
  return (
    <Route
      {...rest}
      render={(props) => {
        console.log(props, "@@");
        // 做一些判断
        const token = window.localStorage.getItem("token");
        if (token) {
          // 存在，就正常显示 component
          return <Component {...props} />;
        } else {
          // 不存在，就直接打到 /login 登录页面
          // 渲染 Redirect 组件, Redirect 是一种 replace 模式
          // ？？使用 rest.path 目前没问题，但是如果有传参时会有问题
          return <Redirect to={`/login?redirect=${props.match.url}`} />;
        }
      }}
    />
  );
}

function App() {
  return (
    <div className="app">
      <Header a="1" b="2" />
      <div className="main">
        <div className="left">
          <NavLink className="link" to="/home" activeClassName="hello">
            Home
          </NavLink>
          <NavLink className="link" to="/about" activeClassName="hello">
            About
          </NavLink>
          <NavLink className="link" to="/help" activeClassName="hello">
            Help
          </NavLink>
          <NavLink className="link" to="/detail/1" activeClassName="hello">
            Detail - 1
          </NavLink>
        </div>
        <div className="right">
          <Switch>
            <Route path="/home" component={Home} />
            <AuthRoute path="/about" component={About} />
            <AuthRoute path="/help" component={Help} />
            <AuthRoute path="/detail/:id" component={Detail} />
            <Route path="/login" component={Login} />
          </Switch>
        </div>
      </div>
    </div>
  );
}

export default withRouter(App);
